//
//  ChatViewController.m
//  MQTT-Demo
//
//  Created by zhaoguoteng on 2020/4/11.
//  Copyright © 2020 zhaoguoteng. All rights reserved.
//

#import "ChatViewController.h"
#import "ChatTextCell.h"
#import "ChatModel.h"
#import "ChatImgCell.h"

@interface ChatViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>

@property(nonatomic, strong) IBOutlet UITableView *tableView;
@property(nonatomic, strong) IBOutlet UITextField *textField;
@property(nonatomic, strong) NSMutableArray *dataList;

@property(nonatomic, strong) IBOutlet NSLayoutConstraint *inputViewBottom;

@end

@implementation ChatViewController

- (void)dealloc {
    [NSNotificationCenter.defaultCenter removeObserver:self];
}

- (NSMutableArray *)dataList {
    if (!_dataList) {
        _dataList = [NSMutableArray array];
    }
    return _dataList;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.estimatedRowHeight = 72.0;
    
//    [NSNotificationCenter.defaultCenter addObserver:self selector:@selector(newMessageAction:) name:@"kNewMessage" object:nil];
    
    [NSNotificationCenter.defaultCenter addObserver:self
                                           selector:@selector(keyboardNotification:)
                                               name:UIKeyboardWillShowNotification
                                             object:nil];
    
    [NSNotificationCenter.defaultCenter addObserver:self
                                           selector:@selector(keyboardNotification:)
                                               name:UIKeyboardWillHideNotification
                                             object:nil];
    
    MQTTManager.share.newMessageBlock = ^(ChatBodyModel *body) {
        if (body.body.count > 0) {
            for (ChatModel *chatModel in body.body) {
                if (chatModel.content) {
                    [self.dataList addObject:chatModel.content];
                }
            }
            
            [self.tableView reloadData];
            
            if (self.dataList.count > 0) {
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataList.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
                });
            }
        }
    };
}

//- (void)newMessageAction:(NSNotification *)sender {
//    if ([sender.object isKindOfClass:ChatBodyModel.class]) {
//        ChatBodyModel *bodyModel = (ChatBodyModel *)sender.object;
//        if (bodyModel.body.count > 0) {
//            for (ChatModel *chatModel in bodyModel.body) {
//                if (chatModel.content) {
//                    [self.dataList addObject:chatModel.content];
//                }
//            }
//
//            [self.tableView reloadData];
//            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.15 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
//                [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.dataList.count - 1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:YES];
//            });
//        }
//    }
//}

#pragma mark - UITextFieldDelegate

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    
    return YES;
}

- (void)keyboardNotification:(NSNotification *)sender {
    CGRect keyboardBounds = [sender.userInfo[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    
    CGFloat safeAreaInsetsBottom = 0;
    if (@available(iOS 11.0, *)) {
        safeAreaInsetsBottom = self.view.safeAreaInsets.bottom;
    }
    
    if ([sender.name isEqualToString:UIKeyboardWillShowNotification]) {
        self.inputViewBottom.constant = -(keyboardBounds.size.height - safeAreaInsetsBottom);
    } else if ([sender.name isEqualToString:UIKeyboardWillHideNotification]) {
        self.inputViewBottom.constant = 0.0;
    }
}

#pragma mark - UITableViewDelegate, UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    id element = self.dataList[indexPath.row];
    
    if ([element isKindOfClass: ChatTextModel.class]) {
        ChatTextCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChatTextCell" forIndexPath:indexPath];
        cell.model = (ChatTextModel *)element;
        return cell;
    } else if ([element isKindOfClass: ChatImgModel.class]) {
        ChatImgCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChatImgCell" forIndexPath:indexPath];
        cell.model = (ChatImgModel *)element;
        
//        [cell setNeedsUpdateConstraints];
//        [cell updateFocusIfNeeded];
        
        return cell;
    }
    
    return nil;
}

#pragma mark -

- (IBAction)sendMsgAction:(UIButton *)sender {
    
    NSString *sendText = [self.textField.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    if (sendText.length > 0) {
        [MQTTManager.share sendMsg: [ChatTextModel body:self.textField.text]];
    }
    
    NSLog(@"## %@", self.textField.text);
    self.textField.text = nil;
}

@end
